<template>
  <div>
    <el-form :model="userForm" :rules="rules" ref="userForm" label-width="100px" style="width:460px">
      <el-form-item label="所属市场：" prop="marketId">
        <el-select v-model="userForm.marketId" placeholder="请选择市场">
          <el-option v-for="(item,index) in store.marketOptions" :key="item.marketId" :label="item.marketName" :value="item.marketId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="角色" prop="userType">
        <el-select v-model="userForm.userType" placeholder="请选择角色">
          <el-option v-for="(item,index) in roleList" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="用户电话:" prop="userMobile">
        <el-input v-model="userForm.userMobile" @change="checkMobile" placeholder="请输入用户电话" clearable></el-input>
      </el-form-item>
      <el-form-item label="用户姓名:" prop="userName">
        <el-input v-model="userForm.userName"  placeholder="请输入用户姓名" clearable></el-input>
      </el-form-item>
      <el-form-item label="用户身份证:" prop="userNo">
        <el-input v-model="userForm.userNo"  placeholder="请输入用户身份证" clearable></el-input>
      </el-form-item>
      <el-form-item label="备注:" prop="userRemark">
        <el-input type="textarea" v-model="userForm.userRemark"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit('userForm')" v-if="this.userId!=1">{{buttonName}}</el-button>
        <el-button @click="turnToList">返回列表</el-button>
        <el-button @click="resetForm('userForm')" v-if="!userId">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
  export default {
    data() {
      return {
        num:0,
        buttonName:'',
        userId: this.$route.params.id,
        userForm:{
          userName:'',
          userType:'',
          marketId: this.$marketId,
          userMobile:'',
          userNo:''
        },
        store:{
          marketOptions:[],
          params:{
            pageSize:10,
            pageIndex:1,
            marketId:this.$marketId,
          },
        },
        rules: {
          marketId:{ required: true, message: '请选择市场', trigger: 'change' },
          userType:{ required: true, message: '请选择用户角色', trigger: 'change' },
          userMobile: [
            { required: true, message: '请填写电话', trigger: 'blur' },
            { min:11 , max:11 , message: '请填写正确的电话', trigger: 'blur' }
          ],
          userName: [
            {  required: true, message: '用户姓名', trigger: 'blur' }
          ],
          desc: { required: true, message: '请填写活动形式', trigger: 'blur' }
        },
        roleList:[]
      };
    },
    watch:{
      '$route'(){
        if (!this.$route.params.id){
          this.userForm = {
            userName:'',
            userType:'',
            marketId: this.$marketId,
            userMobile:'',
            userNo:''
          };
          this.userId = null;
          this.buttonName = '立即创建'
        }
      }
    },
    created(){
      this.getRoleList();
      this.$store.commit('getMarketOptions',this.store);
    },
    methods: {
      getRoleList(){
        const roleId = this.$sess.get('userInfo').roleList[0].roleId;
        if(roleId == 1){
          this.roleList = this.$store.state.userRole.allRolesList
        }else if(roleId == 30){
          this.roleList = this.$store.state.userRole.marketRolesList
        }
      },
      getData(){
        this.$axios.get(this.$api.getUserById,
          { params: {userId: this.userId,marketId:this.userForm.marketId}}).then((res) => {
          if (res){
            this.userForm = res.data.result
            delete  this.userForm.userCreateTime
            delete  this.userForm.userUpdateTime
            delete  this.userForm.shop
            delete  this.userForm.market
          }
        })
      },
      turnToList(){
        this.$router.push('/user/userList')
      },
      checkMobile(){
        this.$axios.get(this.$api.selectUserByMobile,{params: {userMobile: this.userForm.userMobile}})
          .then((res)=>{
            if (res.data.code !=1){
              this.$message({
                message: res.data.msg,
                type: 'error'
              });
              this.userForm.userMobile = ''
            }
          })
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      onSubmit(formName) {
        var requestParam = this.userForm;
        var formData = new FormData();
        for(let i in requestParam){
          formData.append(i,requestParam[i])
        }
        var pathUrl
        if (this.userId != null){
          pathUrl = this.$api.updateUser
        }else{
          pathUrl = this.$api.insertUser
        }
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$axios({
              method: 'post',
              url:  pathUrl,
              data: formData
            }).then((res) => {
              if (res.data.code!=1){
                this.$message({
                  message: '创建失败',
                  type: 'error'
                });
                this.$router.push('/user/userForm')
              }else{
                this.$message({
                  message: '新建成功',
                  type: 'success'
                });
                this.$router.push('/user/userList')
              }
            })
          }else {
            console.log('error submit!!');
            return false;
          }
        });
      },
    },
    activated() {
      this.userId = this.$route.params.id;
      if (this.userId != null){
        this.getData();
        this.buttonName = "立即更新"
      }else{
        this.buttonName = "立即创建"

      }
    },
    deactivated() {

    }
  }
</script>
